using UnityEngine;
using System.Collections;
using System;
using System.ComponentModel;
using TMPro;

public class Fortress : MonoBehaviour
{
    public SpriteRenderer sprite;
    public TextMeshProUGUI numberText;
    public Transform spawnPoint; // 部队生成点
    // 据点属性
    public string faction; // 所属派系
    public Color color; // 派系颜色
    [SerializeField] private int level; //据点等级
    [SerializeField] private FortressLevelSO levelData; // 据点等级属性 
    public int maxTroops = 1000; // 部队上限
    public int minTroops = 200; // 部队最少驻军
    private const int MaxTroopUnit = 100; // 每个部队最大兵力
    private const int MinTroopUnit = 50; // 每个部队最小兵力
    public int currentTroops = 500; // 当前部队
    public int attackPower; //据点当前战力

    public float troopPowerMtp = 0.2f; // 兵力对应的战力乘数

    public float generationTime; // 部队生成时间间隔
    public float thinkTime; // 据点思考时间间隔
    [SerializeField] private float _lastActionTime; // 记录上次行动时间

    public int resourceCost = 10; // 生成部队所需的资源

    public bool isAttacked = false; // 是否被围攻
    public int addSoilderCount = 5; // 驻军增长数
    [Header("对象池相关设置")]
    [SerializeField] private ObjectSO objectData;
    [SerializeField] private ObjectPool troopPool;


    public FortressState currentState;


    // 资源系统引用
    public ResourceSystem resourceSystem;


    public void SetSpriteColor(Color color)
    {
        sprite.color = color;
    }

    private void Start()
    {
        troopPool = ObjectPoolManager.Instance.GetObjectPool(objectData);
        sprite = GetComponentInChildren<SpriteRenderer>();
        numberText = GetComponentInChildren<TextMeshProUGUI>();
        SetSpriteColor(color);
        //设置初始据点状态
        currentState = FortressState.Wait;
        UpdateCommonParams();

        TestGameManager.Instance.OnParamsChanged += UpdateCommonParams;
    }
    private void OnEnable()
    {

    }

    private void OnDisable()
    {
        TestGameManager.Instance.OnParamsChanged -= UpdateCommonParams;
    }
    private void UpdateCommonParams()
    {
        generationTime = TestGameManager.Instance.Day;
        thinkTime = 10 * TestGameManager.Instance.Day;
    }

    private void Update()
    {
        // 更新兵力UI显示
        numberText.text = currentTroops + "";
        // 更新部队战力
        attackPower = MyUtils.DamageFloatToInt(currentTroops * troopPowerMtp);
        // 根据当前状态执行相应行为
        switch (currentState)
        {
            case FortressState.Wait:
                HandleWaitState();
                break;
            case FortressState.Attack:
                HandleAttackState();
                break;
            case FortressState.Defend:
                HandleDefendState();
                break;
            case FortressState.Develop:
                HandleDevelopState();
                break;
            case FortressState.Think:
            default:
                break;
        }
    }

    // 进攻状态逻辑
    private void HandleAttackState()
    {
        // 每隔固定时间生成部队
        if (Time.time - _lastActionTime >= generationTime && currentTroops > minTroops)
        {
            Vector3 target = GetAttackPosition();
            int troopsToSend = currentTroops - minTroops;

            if (MinTroopUnit <= troopsToSend && target != transform.position)
            {
                GenerateSingleTroop(Math.Min(MaxTroopUnit, troopsToSend), target);
                _lastActionTime = Time.time;
            }
        }
    }
    private void HandleDefendState()
    {
        // 防御状态特殊逻辑，例如召回部队等
        // 可以在这里添加防御行为
    }

    private void HandleWaitState()
    {
        //属于派系后开始运行
        if (!string.IsNullOrEmpty(faction))
        {
            currentState = FortressState.Think;
            StartCoroutine(AddSoilders());
            StartCoroutine(FortressThink());

        }
    }

    private void HandleDevelopState()
    {
        // 发展状态特殊逻辑，例如加速生产资源，加速暴兵等
        // 可以在这里添加发展行为
    }

    // 生成驻军的协程
    private IEnumerator AddSoilders()
    {
        while (true)
        {
            if (!isAttacked && resourceSystem.currentResources > 0)
            {
                AddTroopCount(addSoilderCount);
            }
            yield return new WaitForSeconds(generationTime);
        }
    }

    // 据点每隔一段时间思考下一步行动的协程
    private IEnumerator FortressThink()
    {
        while (true)
        {
            // 状态决策逻辑
            if (isAttacked)
            {
                currentState = FortressState.Defend;
            }
            else if (GetEnemyFortress() && currentTroops >= minTroops)
            {
                currentState = FortressState.Attack;
            }
            else if (currentTroops < minTroops)
            {
                currentState = FortressState.Develop;
            }
            else
            {
                currentState = FortressState.Think;
            }

            yield return new WaitForSeconds(thinkTime);
        }
    }



    // 生成单个部队
    private void GenerateSingleTroop(int troopCount, Vector3 targetPosition)
    {
        // 检查游戏是否处于进行状态，并且资源是否足够
        if (TestGameManager.Instance.currentState == TestGameManager.GameState.Playing &&
            resourceSystem.HasEnoughResources(resourceCost))
        {
            // 消耗生成部队所需的资源
            resourceSystem.ConsumeResources(resourceCost);

            // 减少据点当前兵力
            ReduceTroopCount(troopCount);

            // 在生成点实例化部队预制体
            if (troopPool == null)
            {
                Debug.LogError("无法创建部队！需要手动创建对象池:" + objectData.objectName);
                return;
            }
            GameObject troop = troopPool.GetObject(spawnPoint.position, Quaternion.identity);
            Troop troopComponent = troop.GetComponent<Troop>();

            // 设置部队属性
            troopComponent.faction = faction;
            troopComponent.troopCount = troopCount;
            troopComponent.color = color;
            troopComponent.SetSpriteColor(color); // 应用颜色到精灵

            // 设置部队目标位置
            troopComponent.currentState = Troop.TroopState.Wait;
            troopComponent.ownerFortress = this;
            //troopComponent.SetDestination(targetPosition);
        }
    }

    // 寻找非己方据点
    private bool GetEnemyFortress()
    {
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("settlement");
        foreach (GameObject settlement in gameObjects)
        {
            settlement.TryGetComponent<Fortress>(out Fortress fortress);
            if (fortress != null && !faction.Equals(fortress.faction))
            {
                return true;
            }
        }
        return false;
    }

    // 返回进攻的坐标,如果没有目标，返回据点坐标
    private Vector3 GetAttackPosition()
    {
        Vector3 result = transform.position;
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("settlement");
        foreach (GameObject settlement in gameObjects)
        {
            settlement.TryGetComponent<Fortress>(out Fortress fortress);
            if (fortress != null && !faction.Equals(fortress.faction))
            {
                result = fortress.transform.position;
            }
        }
        return result;
    }

    private void AddTroopCount(int count)
    {
        currentTroops += count;
    }

    private void ReduceTroopCount(int count)
    {
        currentTroops -= count;
        // 检查兵力是否归零
        if (currentTroops <= 0)
        {
            ResetFortress();
        }
    }
    // 被攻击，受到伤害
    public void BeAttacked(Troop troop, int beAttackedPower)
    {
        int power = MyUtils.DamageFloatToInt(beAttackedPower * GetDefenseMultiplier()); // 据点减伤
        ReduceTroopCount(power);
    }

    //防守，输出伤害
    public int Defend()
    {
        int power = MyUtils.DamageFloatToInt(attackPower * GetAttackMultiplier()); // 据点减伤
        return power;
    }

    // 获得攻击伤害乘数
    public float GetAttackMultiplier()
    {
        float minAttackMultiplier = 1f;
        foreach (var data in levelData.fortressLevels)
        {
            if (level == data.level)
            {
                return data.attackMultiplier;
            }
            if (data.level == 1)
            {
                minAttackMultiplier = data.attackMultiplier;
            }
        }
        return minAttackMultiplier;
    }

    //获得防守伤害乘数
    public float GetDefenseMultiplier()
    {
        float minDefenseMultiplier = 1f;
        foreach (var data in levelData.fortressLevels)
        {
            if (level == data.level)
            {
                return data.defenseMultiplier;
            }
            if (data.level == 1)
            {
                minDefenseMultiplier = data.defenseMultiplier;
            }
        }
        return minDefenseMultiplier;
    }

    // 重置据点方法
    private void ResetFortress()
    {
        currentTroops = 0;
        faction = ""; // 清空派系
        currentState = FortressState.Wait; // 设为等待状态
        SetSpriteColor(Color.gray); // 可选：设为灰色表示中立

        // 停止所有协程
        StopAllCoroutines();

        // 可以在这里添加其他重置逻辑
        // 如播放特效、音效等
    }

    public void SetFortress(string faction, Color color, int troops)
    {
        this.faction = faction;
        this.color = color;
        SetSpriteColor(color);
        currentTroops += troops;
    }


}

public enum FortressState
{
    Wait, //无派系
    Think, //思考
    Develop, //发展
    Defend,
    Attack


}